<template>
  <!-- prettier-ignore -->
  <div class="p20">
    <!-- {{ dialog }} -->
    <!-- {{ drawer }} -->
    <!-- <pre>{{ userInfo }}</pre> -->
    <!-- <el-button size="small" type="info" plain @click="toggle('dialog', '数据统计')">
      <i class="iconfont icon-calculator"></i>数据统计
    </el-button> -->

    <MainData ref="MainData">
      <template slot="other">
        <div class="dis-ib ml20">
          <!-- <el-button size="small" type="info" plain @click="toggle('dialog', '数据统计')">
            <i class="iconfont icon-calculator"></i>数据统计
          </el-button> -->

          <el-button size="small" type="info" plain  v-if="$store.getters['userInfo/getIsLoading'].sales"
            :disabled="dialog.资源改派.temp.length<=0"
            @click="toggleCustomerChangeList('dialog', '资源改派')">
            <i class="iconfont icon-datamigration"></i>资源改派
          </el-button>
        </div>
      </template>
    </MainData>
    <audio ref="audio" autoplay="autoplay" :src="tempUrl"></audio>

    
    <DialogBinding cn="工作台绑定"></DialogBinding>
    <DialogDSS cn="数据统计"></DialogDSS>
    <DialogRTS cn="资源改派"></DialogRTS>
    <DialogEN cn="编辑备注"></DialogEN>
    <DialogTL cn="编辑标签"></DialogTL>
    <DialogTelM cn="拨号管理"></DialogTelM>
    <DrawerCDR cn="成交登记"></DrawerCDR>
    <DrawerTSF cn="会话存档"></DrawerTSF>
    <DialogSAlist cn="报表审核list"></DialogSAlist>
    <DialogSAitem cn="报表审核item"></DialogSAitem>
    <DialogMS></DialogMS>
    <DialogBZlist></DialogBZlist>
    <DialogLY></DialogLY>
    <!-- 以上cn属性无实际作用，仅标识尔 -->
  </div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
import { bus } from '@/main.js';
import BenzAMRRecorder from 'benz-amr-recorder';
export default {
  name: 'index',
  components: {
    MainData: () => {
      return import('./mainData/mainData.vue');
    },
    DialogBinding: () => {
      return import('./dialog/工作台资源绑定.vue');
    },
    DialogDSS: () => {
      return import('./dialog/数据统计.vue');
    },
    DialogRTS: () => {
      return import('./dialog/资源改派.vue');
    },
    DialogEN: () => {
      return import('./dialog/编辑备注名.vue');
    },
    DialogTL: () => {
      return import('./dialog/编辑标签.vue');
    },
    DialogTelM: () => {
      return import('./dialog/拨号管理.vue');
    },
    DrawerCDR: () => {
      return import('./drawer/成交登记.vue');
    },
    DrawerTSF: () => {
      return import('./drawer/会话存档.vue');
    },
    DialogSAlist: () => {
      return import('./dialog/报表审核list.vue');
    },
    DialogSAitem: () => {
      return import('./dialog/报表审核item.vue');
    },
    DialogMS: () => {
      return import('./dialog/编辑描述.vue');
    },
    DialogBZlist: () => {
      return import('./dialog/编辑备注列表.vue');
    },
    DialogLY: () => {
      return import('./dialog/查看录音.vue');
    },
  },
  data() {
    return {
      isDev: process.env.NODE_ENV !== 'development',
      tempUrl: '',
      playRec: null, //播放对象
      voiceActive: null,
    };
  },
  computed: {
    ...mapState(['userInfo', 'conditional', 'dialog', 'drawer']),
  },
  methods: {
    ...mapMutations(['toggleCustomerChangeList']),
    test: function() {},
    openRecording(_url) {
      let thisVue = this;
      if (thisVue.voiceActive) {
        thisVue.stopPlayVoice();
        return;
      }
      if (thisVue.playRec !== null) {
        thisVue.stopPlayVoice();
      }
      thisVue.playRec = new BenzAMRRecorder();
      //⚠️注意跨域问题
      thisVue.playRec
        .initWithUrl(_url)
        .then(function() {
          thisVue.voiceActive = true;
          thisVue.playRec.play();
          thisVue.playRec.onEnded(function() {
            thisVue.voiceActive = null;
          });
        })
        .catch(e => {
          if (e.message == 'Failed to decode.') {
            thisVue.$message.error(
              '该录音文件在Web页面上无法播放，请下载到本地使用更专业的软件播放，如迅雷影音等',
              {
                duration: 1000 * 7,
              },
            );
          } else {
            thisVue.$message.error('录音播放失败');
          }
        });
    },
    //停止播放
    stopPlayVoice() {
      if (this.playRec.isPlaying()) {
        this.playRec.stop();
      }
    },
    toggle: function(type, key) {
      this.$store.commit('toggleDialog', { type, key });
    },
    clinchADeal(row) {
      this.$store.commit('toggleDialog', { type: 'drawer', key: '成交登记' });
    },
    handleClose(done) {
      done();
    },
  },
  beforeCreate: function() {
    let ceid = this._.get(this.$route.query, 'companyEmployeeId');
    let arg = { companyEmployeeId: ceid };
    if (this._.has(this.$route.query, 'CompanyDepartmentCompanyId')) {
      arg['CompanyDepartmentCompanyId'] = this._.get(
        this.$route.query,
        'CompanyDepartmentCompanyId',
      );
    }
    this.$loading();
    this.$api
      .getCompanyEmployee(arg)

      .then(res => {
        if (res.code == 200) {
          return Promise.resolve(res.data);
        }
      })
      .then(info => {
        let 分公司id = this._.get(
          arg,
          'CompanyDepartmentCompanyId',
          info.company_Department_Company_Id,
        );
        let 分公司名 = this._.get(
          { 32: '二分', 33: '七分', 105: '四分', 143: '六分' },
          分公司id,
        );
        this.$store.commit(
          'userInfo/init',
          Object.assign(info, {
            company_Department_Company_Id: 分公司id,
            分公司名: 分公司名,
          }),
        );
        return Promise.resolve({
          ceid: info.company_Employee_Id,
          cdcid: 分公司id,
          lv: info.company_Post_Id,
        });
      })
      .then(res => {
        let pArr = [
          this.$api.getResourceChannels({
            companyDepartmentCompany_Id: res.cdcid,
            companyEmployeeId: res.ceid,
            // type: 1, //类型ID 0 表单渠道 1 外联渠道，默认值为1-外联渠道//本项目确认传1
            // 又修改为不传type则全部下发
          }), // 0
          this.$api.getEsCompanyList({
            companyDepartmentCompany_Id: res.cdcid,
            companyEmployeeId: res.ceid,
          }), // 1
          this.$api.getCrmProduct({
            companyDepartmentCompany_Id: res.cdcid,
          }), // 2
          this.$api.getPayType({}), // 3
          this.$api.getTagList({
            company_Department_Company_Id: res.cdcid,
          }), // 4
          this.$api.getRFReportForms({
            companyEmployeeId: res.ceid,
          }), // 5
        ];
        pArr.push(res);

        return Promise.all(pArr);
      })
      .then(res => {
        let arg = res.pop(); //从数组中删除最后一个元素，并返回该元素的值，初学乍练备忘一下
        if (res[0].code == 200 && res[0].data.length > 0) {
          this.isDev && console.log('进线渠道 获取成功');
          this.$store.commit('conditional/initOptions', {
            key: 'resourceChannels',
            data: res[0].data,
          });
        }
        if (res[1].code == 200 && res[1].data.length > 0) {
          this.isDev && console.log('工作台 获取成功');
          this.$store.commit('conditional/initOptions', {
            key: 'workbench',
            data: res[1].data,
          });
          this.$store.commit('conditional/initDEFAULT', {
            key: 'workbench',
          });
        }
        if (res[2].code == 200 && res[2].data.length > 0) {
          this.isDev && console.log('分公司产品信息 获取成功');
          this.$store.commit('conditional/initOptions', {
            key: 'crmProduct',
            data: res[2].data,
          });
        }
        if (res[3].code == 200 && res[3].data.length > 0) {
          this.isDev && console.log('支付方式 获取成功');
          this.$store.commit('conditional/initOptions', {
            key: 'payType',
            data: res[3].data,
          });
        }
        if (res[4].code == 200 && res[4].data.length > 0) {
          this.isDev && console.log('标签信息 获取成功');
          this.$store.commit('conditional/initOptions', {
            key: 'theLabel',
            data: res[4].data,
          });
        }
        if (res[5].code == 200 && res[5].data.length >= 0) {
          this.isDev && console.log('资源报表 获取成功');
          this.$store.commit('conditional/initOptions', {
            key: 'rFReportForms',
            data: res[5].data,
          });
        }
        let b = this.$store.getters['userInfo/getIsLoading'];
        let pArr = [];
        if (b.sales) {
          pArr.push(
            this.$api.getCompanyEmployeeList(
              {
                companyDepartmentCompany_Id: arg.cdcid,
              },
              {},
              1, //接口有多个版本，这里用v1版本
            ),
          );
        }
        if (b.departmen) {
          pArr.push(
            this.$api.getCompanyDepartmentList({
              companyDepartmentCompany_Id: arg.cdcid,
            }),
          );
        }
        return Promise.all(pArr);
      })
      .then(res => {
        let b = this.$store.getters['userInfo/getIsLoading'];
        if (b.sales && res[0].code == 200 && res[0].data.length > 0) {
          this.isDev && console.log('归属员工 获取成功');
          this.$store.commit('conditional/initOptions', {
            key: 'belongToSales',
            data: res[0].data,
          });
          this.$store.commit('conditional/setEmployeeData', res[0].data);
        }
        if (b.departmen && res[1].code == 200 && res[1].data.length > 0) {
          this.isDev && console.log('归属部门 获取成功');
          this.$store.commit('conditional/initOptions', {
            key: 'department',
            data: res[1].data,
          });
        }
      })
      .catch(err => {
        this.$message({
          message: '初始化选项异常，请联系管理员处理',
          type: 'error',
        });
      })
      .finally(() => {
        this.$loading().close();
      });
  },
  created: function() {},
  beforeMount: function() {},
  mounted: function() {
    bus.$on('录音stop', e => {
      console.log('录音stop');
      this.stopPlayVoice();
      // this.tempUrl = '';
      // this.$refs.audio.pause();
    });
    bus.$on('录音play', e => {
      console.log('录音play');
      this.openRecording(e.soundAddress);
      // this.tempUrl = e.soundAddress;
      // this.$refs.audio.play();
    });
    bus.$on('download', e => {
      let a = document.createElement('a');
      fetch(e.url)
        .then(res => {
          return res.blob();
        })
        .then(blob => {
          let href = window.URL.createObjectURL(blob);
          a.href = href;
          a.download = e.fileName;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
        });
    });
  },
  beforeUpdate: function() {},
  updated: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less"></style>
